package com.haiheng.visualhandheld

import android.Manifest
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import androidx.annotation.RequiresApi
import com.haiheng.common.activity.RouterActivity
import com.haiheng.common.constant.RourePage
import com.haiheng.common.constant.RourePath
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.toast.KeyboardUtils
import com.haiheng.module_main.service.ScansReceiver
import com.haiheng.visualhandheld.databinding.ActivityMainBinding


class MainActivity : RouterActivity() {
    private var broadcastReceiver: ScansReceiver? = null


    var binding: ActivityMainBinding? = null
    override fun controllerId(): Int {
        return R.id.nav_host_fragment_main
    }


    /**
     *   ("SMART_DEPLOYMENT"),
    ("BOOK_OFF_SHELVING"),
    ("BOOK_RE_SHELVING"),
    FIND_AND_LOCATE("FIND_AND_LOCATE"),
    BOOK_RETIREMENT("BOOK_RETIREMENT"),
    BOOK_INVENTORY("BOOK_INVENTORY"),
    ASSET_INVENTORY("ASSET_INVENTORY"),
    DATA_SYNCHRONIZATION("DATA_SYNCHRONIZATION"),
    ALARMED_BOOKS("ALARMED_BOOKS"),
    MIS_SHELVED_CORRECTION("MIS_SHELVED_CORRECTION"),
     */
    override fun navigation(name: RourePage, bundle: Bundle?) {
        when (name) {
            RourePage.MAIN -> navigate(RourePath.MAIN_FRAGMENT, bundle)
            RourePage.LOGIN -> popBackStack(R.id.login_graph,false)
            RourePage.SETTING_PAGE ->navigate(RourePath.SETTING_PAGE_FRAGMENT,bundle)
            RourePage.SINGLE_VOLUME_DEPLOYMENT ->navigate(RourePath.SINGLE_VOLUME_DEPLOYMENT_FRAGMENT,bundle)
            RourePage.SMART_DEPLOYMENT ->navigate(RourePath.SMART_DEPLOYMENT_FRAGMENT,bundle)
            RourePage.BOOK_WITHDRAWAL ->navigate(RourePath.BOOK_WITHDRAWAL_FRAGMENT,bundle)
            RourePage.BOOK_OFF_SHELVING ->navigate(RourePath.BOOK_OFF_SHELVING_FRAGMENT,bundle)
            RourePage.BOOK_RE_SHELVING ->navigate(RourePath.BOOK_RE_SHELVING_FRAGMENT,bundle)
            RourePage.FIND_AND_LOCATE ->navigate(RourePath.FIND_AND_LOCATE_FRAGMENT,bundle)
            RourePage.BOOK_RETIREMENT ->navigate(RourePath.BOOK_RETIREMENT_FRAGMENT,bundle)
            RourePage.BOOK_INVENTORY ->navigate(RourePath.BOOK_RE_SHELVING_FRAGMENT,bundle)
            RourePage.ASSET_INVENTORY ->navigate(RourePath.ASSET_INVENTORY_FRAGMENT,bundle)
            RourePage.DATA_SYNCHRONIZATION ->navigate(RourePath.DATA_SYNCHRONIZATION_FRAGMENT,bundle)
            RourePage.ALARMED_BOOKS ->navigate(RourePath.ALARMED_BOOKS_FRAGMENT,bundle)
            RourePage.MIS_SHELVED_CORRECTION ->navigate(RourePath.MIS_SHELVED_CORRECTION_FRAGMENT,bundle)
            RourePage.BOOK_CAR_LOGIN_RESULT ->navigate(RourePath.BOOK_CAR_LOGIN_RESULT_FRAGMENT,bundle)
            RourePage.BOOK_CAR_SCAN ->navigate(RourePath.BOOK_CAR_SCAN_FRAGMENT,bundle)
            RourePage.BOOK_CAR_INFO ->navigate(RourePath.BOOK_CAR_INFO_FRAGMENT,bundle)
            RourePage.BOOK_CAR_SHELF ->navigate(RourePath.BOOK_CAR_SHELF_FRAGMENT,bundle)
            RourePage.BOOK_CAR_WEB ->navigate(RourePath.BOOK_CAR_WEB_FRAGMENT,bundle)
            RourePage.BOOK_CAR_BOOK_DELIVER_ORDER ->navigate(RourePath.BOOK_CAR_BOOK_DELIVER_ORDER_FRAGMENT,bundle)
        }
    }

    override fun setTitleBgColor(color: Int) {
    }

    override fun isHasOperation(): Boolean {
        return false
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTheme(R.style.AppTheme)
        window.setFormat(PixelFormat.TRANSLUCENT)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)

        binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(binding!!.root)
//        BarUtils.setStatusBarColor(window,getColor(R.color.theme))
        requestPermissions(99)
        initBroadcast()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.getAction() == MotionEvent.ACTION_DOWN) {
            var v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                KeyboardUtils.hideSoftInput(this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationOnScreen(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.rawX > left && event.rawX < right && event.rawY > top && event.rawY < bottom)
        }
        return false
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100 && grantResults.size == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            LogUtils.e("权限申请成功")
        } else {
            LogUtils.e("权限申请失败")
        }
    }

    // 请求权限
    fun requestPermissions(requestCode: Int) {
        try {
            LogUtils.e("请求权限：${Build.VERSION.SDK_INT}")
            if (Build.VERSION.SDK_INT >= 23) {

                if (Build.VERSION.SDK_INT >= 31){
                    if (!Environment.isExternalStorageManager()) {
                        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                        startActivity(intent)
                        return
                    }
                }
                val requestPerssionArr = ArrayList<String>()
                val hasCamrea = checkSelfPermission(Manifest.permission.CAMERA)
                if (hasCamrea != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.CAMERA)
                }
                val hasSdcardRead = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                if (hasSdcardRead != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
                val hasSdcardWrite = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                if (hasSdcardWrite != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                }
                LogUtils.e("requestPerssionArr hasCamrea ：${hasCamrea}  hasSdcardRead ：${hasSdcardRead}  hasSdcardWrite ：${hasSdcardWrite}")
                // 是否应该显示权限请求
                if (requestPerssionArr.size >= 1) {
                    val requestArray = arrayOfNulls<String>(requestPerssionArr.size)
                    for (i in requestArray.indices) {
                        requestArray[i] = requestPerssionArr[i]
                    }
                    requestPermissions(requestArray, requestCode)
                }
            }
        } catch (e: Exception) {
            LogWriter.e("请求权限异常：${e.toString()}")
            e.printStackTrace()
        }
    }


    private fun initBroadcast() {
        if (broadcastReceiver == null) {
            val filter = IntentFilter()
            filter.addAction("android.scanservice.action.UPLOAD_BARCODE_DATA")
            filter.addAction("com.safeuem.doublebird.appReadyToInstall")
            broadcastReceiver = ScansReceiver()
            registerReceiver(broadcastReceiver, filter)
        }
    }
}
